package teach

import (
	"gitee.com/chenhonghua/ginorigin/config/storage/database"
	"gitee.com/chenhonghua/ginorigin/config/system/zap"

	"gorm.io/gorm"
)

// 根据模型建表
func createTalbes() {
	if nil == database.GetConnection() {
		return
	}
	zap.LOGGER.Debug("开始创建教学数据库表")
	database.CreateTables(Nation{}, Author{}, CourseType{}, Course{}, Chapter{})
}

var nation1 Nation = Nation{CnName: "测试国家01", EnName: "testcountry01", EnglishAbbreviation: "TC1"}
var author1 Author = Author{Name: "测试作者01", Nation: nation1}
var courseType1 CourseType = CourseType{TypeName: "测试课程类型01"}

var metadataCourse1 Course = Course{Title: "测试课程001", Chapters: []Chapter{{Sequence: 0, Title: "测试章节001"}, {Sequence: 1, Title: "测试章节002"}}}
var metadataCourse2 Course = Course{Title: "测试课程002", Chapters: []Chapter{{Sequence: 0, Title: "测试章节001"}, {Sequence: 1, Title: "测试章节002"}}}
var metadataCourse3 Course = Course{Title: "测试课程002", Chapters: []Chapter{{Sequence: 0, Title: "测试章节001"}, {Sequence: 1, Title: "测试章节002"}}}

// 初始数据导入
func importMetaData() {
	if nil == database.GetConnection() {
		return
	}
	// 关联查询，Preload内是结构体属性名，如果有多层嵌套，就用"."逐层声明属性名
	// st := time.Now().Nanosecond()
	course, err := metadataCourse1.FindBySelf()
	// et := time.Now().Nanosecond()
	// useTimeNanoSecond := et - st
	// j, _ := json.Marshal(course)
	// zap.LOGGER.Debug(fmt.Sprintf("查询数据库数据（用时%d纳秒）\n", useTimeNanoSecond))
	// zap.LOGGER.Debug(string(j))
	if nil == err && len(course) > 0 {
		zap.LOGGER.Info("教学数据库已有数据")
		return
	} else {
		zap.LOGGER.Info("教学数据库没有数据，准备进行数据导入")
	}
	// st = time.Now().Nanosecond()
	if err := database.Transaction(func(tx *gorm.DB) error {
		if err := tx.Create(&nation1).Error; nil != err {
			return err
		}
		author1.Nation = nation1
		if err := tx.Create(&author1).Error; nil != err {
			return err
		}
		if err := tx.Create(&courseType1).Error; nil != err {
			return err
		}
		metadataCourse1.AuthorId = author1.ID
		metadataCourse1.CourseTypeId = courseType1.ID
		if err := tx.Create(&metadataCourse1).Error; nil != err {
			return err
		}
		metadataCourse2.AuthorId = author1.ID
		metadataCourse2.CourseTypeId = courseType1.ID
		if err := tx.Create(&metadataCourse2).Error; nil != err {
			return err
		}
		if err := tx.Create(&metadataCourse3).Error; nil != err {
			return err
		}
		return nil
	}); err != nil { // 事务异常业务处理
		zap.LOGGER.Error(err.Error(), zap.Error(err))
	}
	// et = time.Now().Nanosecond()
	// zap.LOGGER.Debug(fmt.Sprintf("数据库导入完成（用时%d纳秒）\n", et-st))
}
